package com.nlecloud.bc.controller;

import com.nlecloud.bc.controller.dto.UserDTO;
import com.nlecloud.bc.interceptor.AuthTokenStorage;
import com.nlecloud.bc.model.Result;
import com.nlecloud.bc.model.User;
import com.nlecloud.bc.service.IUserService;
import com.nlecloud.bc.service.contract.IUserContractService;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.List;

/**
 * @author warrior
 * @description 用户操作API
 */
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
   private IUserContractService userContractService;

    /**
     * 注册用户
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("user/register")
    public Result register(@RequestParam("username")String username,@RequestParam("password")String password){
        userService.register(username,password);
        return Result.succeed("注册用户成功");
    }

    /**
     * 用户登入
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("user/login")
    public Result<String> login(@RequestParam("username") String username, @RequestParam("password")String password){
        String token = userService.login(username,password);
        return Result.succeed(token,"登入成功");
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("user/info")
    public Result<UserDTO> getUserInfo() throws ContractException {
        User user = AuthTokenStorage.getUser();
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        //获取账户余额
        BigInteger amount = userContractService.getBalance(user.getId());
        userDTO.setAmount(amount);
        return Result.succeed(userDTO);
    }


    /**
     * 退出登入
     * @return
     */
    @PostMapping("user/logout")
    public Result logout(){
        AuthTokenStorage.clearUser();
        return Result.succeed("退出登入成功");
    }

    /**
     * 获取所有用户列表
     * @return
     */
    @GetMapping("list/all/user")
    public Result<List<UserDTO>> listAllUser(){
        List<UserDTO> userDTOS = userService.listAllUser();
        return Result.succeed(userDTOS);
    }
}
